package com.zhq.base;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;


import com.gyf.barlibrary.ImmersionBar;
import com.zhq.R;
import com.zhq.apputil.base.RequestPermissionOnListener;
import com.zhq.apputil.utils.PermissionManage;
import com.zhq.apputil.utils.ScreenUtils;
import com.zhq.apputil.widget.TitleBarLayout;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.constraintlayout.widget.Constraints;

import butterknife.ButterKnife;


/**
 * @Author: Zhq
 * @Date: 2019/1/30 10:52
 * @Description: 抽象基类activity，统一模板管理子类activity
 */
public abstract class BaseActivity<V, T extends BasePresenter<V>> extends AppCompatActivity {
    public abstract int getLayoutUrl();//获得布局地址

    public abstract void registerById();//注册ID

    public abstract TitleBarLayout getTitleBarLayout();

    public abstract void initData();//初始化页面数据

    public T presenter;
    public boolean isFirstInit = true;
    private long exitTime = 0;

    // 实例化presenter
    protected abstract T initPresenter();

    private ImmersionBar mImmersionBar;
    protected TitleBarLayout titleBarLayout;
    private RequestPermissionOnListener permissionOnListener;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initImmersionBar(R.color.transparent);  //沉浸式状态栏
        setContentView(getLayoutUrl());
        addTitleBarView();
        ButterKnife.bind(this);
        presenter = initPresenter();
        if (presenter != null) {
            presenter.attach((V) this);
        }
        //绑定VIew
        registerById();
    }


    /****
     * 添加TitleBar控件，开发人员不用操心视图xml头部元素
     */
    public void addTitleBarView() {
        View rootView = ((ViewGroup) findViewById(android.R.id.content)).getChildAt(0);
        if (rootView != null && getTitleBarLayout() != null) {
            titleBarLayout = getTitleBarLayout();
            titleBarLayout
                    .setTitleBarBackDrawableLeftSrc(R.drawable.ic_arrow_back_white_24dp)
                    .setTitleBarBackFontColor(R.color.white)
                    .setTitleBarTitleColor(R.color.white)
                    .setTitleRightFontColor(R.color.white)
                    .setTitleBarTitleFontSize(15)
                    .setTitleBarFontSize(15)
                    .setTitleBarBackground(getResources().getDrawable(R.drawable.divider_bottom_gray_line))
                    .setBackDrawableLeftWidthHeight(24, 24)
                    .setFontLeftPadding(TitleBarLayout.LEFT, 10)
                    .setFontRightPadding(TitleBarLayout.RIGHT, 10)
                    .setTitleBarBackOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            finishActivity();
                        }
                    })
                    .build();
            if (rootView instanceof LinearLayout) {
                LinearLayout linearParent = (LinearLayout) rootView;
                linearParent.addView(titleBarLayout, 0);
            } else if (rootView instanceof RelativeLayout) {
                RelativeLayout relativeParent = (RelativeLayout) rootView;
                titleBarLayout.setId(R.id.titleBar_id);
                relativeParent.addView(titleBarLayout, 0);
                View view = relativeParent.getChildAt(1);
                RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) view.getLayoutParams();
                params.addRule(RelativeLayout.BELOW, 0);
                view.setLayoutParams(params);
            }else if (rootView instanceof ConstraintLayout) {
                ConstraintLayout constraintLayout = (ConstraintLayout) rootView;
                titleBarLayout.setId(R.id.titleBar_id);
                constraintLayout.getLayoutParams();

                ConstraintLayout.LayoutParams params = new ConstraintLayout.LayoutParams(
                        0, ScreenUtils.dpToPx(getResources(), 50)
                );
                params.startToStart = Constraints.LayoutParams.PARENT_ID;
                params.endToEnd = Constraints.LayoutParams.PARENT_ID;
                params.topToTop = Constraints.LayoutParams.PARENT_ID;
                titleBarLayout.setLayoutParams(params);

                constraintLayout.addView(titleBarLayout, 0);
            }
        }
    }

    public void gotoActivity(Class<? extends Activity> activityClass) {
        Intent intent = new Intent(this, activityClass);
        startActivity(intent);
        overridePendingTransition(R.anim.activity_in_rightleft, R.anim.activity_out_rightleft);
    }

    public void gotoActivity(Class<? extends Activity> activityClass, Bundle bundle) {
        Intent intent = new Intent(this, activityClass);
        intent.putExtras(bundle);
        startActivity(intent);
        overridePendingTransition(R.anim.activity_in_rightleft, R.anim.activity_out_rightleft);
    }

    protected void gotoActivityForResult(Class<? extends Activity> activityClass, Bundle bundle, int requestCode) {
        Intent intent = new Intent(this, activityClass);
        intent.putExtras(bundle);
        startActivityForResult(intent, requestCode);
    }

    protected void gotoActivitySetResult(Class<? extends Activity> activityClass, Bundle bundle, int requestCode) {
        Intent intent = new Intent(this, activityClass);
        intent.putExtras(bundle);
        setResult(requestCode, intent);
        finishActivity();
    }


    /***
     * 绑定权限
     * @param onListener
     */
    public void setOnRequestPermissionListener(RequestPermissionOnListener onListener) {
        this.permissionOnListener = onListener;
    }

    /**
     * 重写关闭Activity
     **/
    public void finishActivity() {
        finish();
        closeSoftKeyboard();
    }

    /**
     * 沉浸栏颜色
     */
    protected void initImmersionBar(int color) {
        mImmersionBar = ImmersionBar.with(this);
        if (color != 0) {
            mImmersionBar.statusBarColor(color);
        }
        mImmersionBar.init();
    }

    /**
     * TOUCH关闭软键盘
     **/
    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                closeSoftKeyboard();
                break;
        }
        return super.onTouchEvent(ev);
    }

    @Override
    public void onPause() {
        super.onPause();
    }


    @Override
    protected void onResume() {
        super.onResume();
        if (isFirstInit) {
            isFirstInit = false;
            initData();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PermissionManage.SDK_PERMISSION_REQUEST) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                if (permissionOnListener != null) {
                    permissionOnListener.requestPermission();
                }
            }
        } else if (requestCode == PermissionManage.REQUEST_CONTACT_PHONE_PERMISSION) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                if (permissionOnListener != null) {
                    permissionOnListener.requestPermission();
                }
            } else {
                Toast.makeText(BaseActivity.this, "获取联系人的权限申请失败", Toast.LENGTH_SHORT).show();
            }
        }

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

    }

    /**
     * 关闭软键盘
     **/
    public  void closeSoftKeyboard() {
        if (getCurrentFocus() != null &&getCurrentFocus().getWindowToken() != null) {
            InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            manager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }
    /**
     * 双击退出
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                finishActivity();
            }
            return false;
//
//            if (this instanceof MainActivity) {
//
//            } else if (this instanceof LoginActivity) {
//                //销毁当前App应用进程
//                finishActivity();
//                android.os.Process.killProcess(android.os.Process.myPid());
//                System.exit(10);
//            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        if (presenter != null) {
            presenter.detachView();
        }
        if (mImmersionBar != null) {
            mImmersionBar.destroy();
        }
        super.onDestroy();

    }

}
